package cc.woori.mobile;

import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cc.woori.mobile.bean.ChurchServiceEntry2;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;

public class ModifyServiceServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {
	doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {

	String mode = req.getParameter("mode");
	String reqKey = req.getParameter("key");
	Key key = KeyFactory.stringToKey(reqKey);

	PersistenceManager pm = PMF.get().getPersistenceManager();

	try {

	    ChurchServiceEntry2 entry = pm.getObjectById(
		    ChurchServiceEntry2.class, key);

	    if (mode.equalsIgnoreCase("delete")) {
		pm.deletePersistent(entry);
	    } else if (mode.equalsIgnoreCase("edit")) {
		String title = req.getParameter("title");
		String description = req.getParameter("description");
		String pastor = req.getParameter("pastorName");
		String date = req.getParameter("date");
		String verse = req.getParameter("verse");
		String svcVideoUrl = req.getParameter("videoUrl");
		String svcAudioUrl = req.getParameter("audioUrl");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

		Transaction tx = pm.currentTransaction();

		tx.begin();
		entry.setTitle(title);
		entry.setDescription(new Text(description));
		entry.setPastor(pastor);
		entry.setPublishDate(sdf.parse(date));
		entry.setVerse(verse);
		entry.setSvcAudioUrl(svcAudioUrl);
		entry.setSvcVideoUrl(svcVideoUrl);
		pm.makePersistent(entry);
		tx.commit();

	    }
	} catch (Exception e) {
	} finally {
	    if (pm != null) {
		pm.close();
	    }
	}

	RequestDispatcher view = req
		.getRequestDispatcher("/admin/adminService.jsp");
	view.forward(req, resp);
    }
}
